import browser from "webextension-polyfill";
import { saveDataToLocalStorage, getDataFromLocalStorage } from "@src/utils/common";
import { systemList } from "@src/globalData/enum";

/** 在background中获取对应tab的cookie */
export const cookiesGetAll = async (urlCookie:string) => {
  const tabs = await browser.tabs.query({ url:urlCookie })
  const url = new URL(tabs?.[0]?.url || '')
  const cookies = await browser.cookies.getAll({ domain: url.host})
  return cookies
}

/** 获取tab的唯一标记 */
export const getTabMark = (url:URL) => {
  const {href} = url
  const mark = systemList.find(val => {
    const reg = new RegExp(`^${val}`)
    return reg.test(href)
  })
  
  return mark || 'not found'
}

/** 保存 现货市场中长期 子系统中的 headers 信息 */
export const saveSportMarketZcqHeaders = (headers:HeadersInit) => {
  saveDataToLocalStorage(JSON.stringify(headers), 'spotMarketZcqHeaders')
}
/** 获取 现货市场 中长期的 headers 信息 */
export const getSportMarketZcqHeaders = async ():Promise<HeadersInit> => {
  try {
    const headers = await getDataFromLocalStorage('spotMarketZcqHeaders')
    return Promise.resolve(headers ? JSON.parse(headers as string) : headers)
  }catch(e) {
    console.error(e)
    return Promise.reject(e)
  }
}

/** 保存 现货市场的 headers 信息 */
export const saveSportMarketHeaders = (headers:HeadersInit) => {
  saveDataToLocalStorage(JSON.stringify(headers), 'spotMarketHeaders')
}
/** 获取 现货市场的 headers 信息 */
export const getSportMarketHeaders = async ():Promise<HeadersInit> => {
  try {
    const headers = await getDataFromLocalStorage('spotMarketHeaders')
    return Promise.resolve(headers ? JSON.parse(headers as string) : headers)
  }catch(e) {
    console.error(e)
    return Promise.reject(e)
  }
}

/** 保存 现货市场的 headers 信息 */
export const saveMainSystemHeaders = (headers:HeadersInit) => {
  saveDataToLocalStorage(JSON.stringify(headers), 'mainSystemHeaders')
}
/** 获取 现货市场的 headers 信息 */
export const getMainSystemHeaders = async ():Promise<HeadersInit> => {
  try {
    const headers = await getDataFromLocalStorage('mainSystemHeaders')
    return Promise.resolve(headers ? JSON.parse(headers as string) : headers)
  }catch(e) {
    console.error(e)
    return Promise.reject(e)
  }
}

/** 保存 主系统 用户信息 */
export const saveStorageUserinfo = (userInfo:any) => {
  saveDataToLocalStorage(JSON.stringify(userInfo), 'spotMarketUserinfo')
}
/** 获取 主系统 用户信息 */
export const getStorageUserinfo = async ():Promise<any> => {
  try {
    const userInfo:any = await getDataFromLocalStorage('spotMarketUserinfo')
    if(userInfo?.userName !== import.meta.env.VITE_APP_ACCOUNT) {
      saveStorageUserinfo('')
      const errTip = '实际账号与打包配置账号不一致'
      console.error(errTip)
      return Promise.reject(new Error(errTip))
    }
    return Promise.resolve(userInfo ? JSON.parse(userInfo as string) : userInfo)
  }catch(e) {
    console.error(e)
    return Promise.reject(e)
  }
}

export const closeOtherTabs = (currentTabId:number) => {
  chrome.tabs.query({}, function(tabs) {
    // 关闭所有其他标签页
    tabs.forEach((tab:chrome.tabs.Tab) => {
      if (tab.id === currentTabId || !tab?.id) return 
      if(/^chrome:/.test(tab?.url || '')) return
      chrome.tabs.remove(tab.id);
    });
  });
}